package com.kdtech.analyse.outside;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.alibaba.fastjson.JSONObject;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;

/**
 * 香港商报
 * @author Persh
 *
 */
public class YzzkNewsAnalyse implements AnalyseNews {
	
	private static final String[] regex={
		"https://www.yzzk.com/cfm/content_archive.cfm\\?docissue=[0-9]{4}-[0-9]{2}&id=[0-9]+"
	};
	
	
	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}		
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();		
				
		news.setUrl(url);		
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
//		Document doc=Jsoup.parse(htmltxt);
//		title =doc.select("h1#passageTitle").text();
//		content=HtmlCleaner.getContentHtml(url,doc.select("div.passage"));
//		author=JSoupUtils.matchAuthor(doc, "來源：");
//		date=DateUtils.matchDate(doc.select("div.ti_con").text());
		
		if(url.matches("https://www.yzzk.com/cfm/content_archive.cfm.*")){
			String issue = StringUtils.substringAfter(url, "issue=");
			String id = StringUtils.substringBetween(url, "id=", "&doc");
//			System.err.println("id="+id);
//			System.err.println("issue="+issue);
			url = "https://www.yzzk.com/cfm/contentxml.cfm\\?issue=" + issue + "&id=" + id;
			urlMeta = CrawlHTML.responseToURL(url);
			if(urlMeta!=null){
				htmltxt = urlMeta.getHtml();
			}
//			System.err.println("html="+htmltxt);
			Document doc=Jsoup.parse(htmltxt);
			content = doc.select("item[nodeid="+id+"] description").text();
			title = doc.select("item[nodeid="+id+"] title").text();
			date = System.currentTimeMillis();
//			try{
//				JSONObject jsonObj = JSONObject.parseObject(htmltxt);
//				title = jsonObj.getString("Title");
//				date = DateUtils.matchDate(jsonObj.getString("CreatedDate"));
//				content = jsonObj.getString("channel");
//				author = jsonObj.getString("CreatorName");
//			}catch(RuntimeException e){
//				e.printStackTrace();
//			}
		}
		
		if(StringUtils.isBlank(title)){
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);	
		
		return news;
	}
	
	

	

	
}
